import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from '../api/api.service';
import { ApiUrl } from '../api/ApiUrl';
import { AlertController, LoadingController , Platform } from '@ionic/angular';
import { ArticleVO } from '../vo/ArticleVO';
import { AdvertiseVO } from './../vo/AdvertiseVO';
import { Router } from '@angular/router';

@Component({
  selector: 'app-companydynamic',
  templateUrl: './companydynamic.page.html',
  styleUrls: ['./companydynamic.page.scss'],
})
export class CompanydynamicPage implements OnInit {
  slideItems: AdvertiseVO[] = [
    { 'iid': 1, 'ccontent': 'title1', 'cpicpath': 'assets/lb/lb02.png', 'cskiplinks': '' },
    { 'iid': 2, 'ccontent': 'title2', 'cpicpath': 'assets/lb/lb01.png', 'cskiplinks': '' },
    { 'iid': 3, 'ccontent': 'title3', 'cpicpath': 'assets/lb/lb03.png', 'cskiplinks': '' }
  ];
  itype: any;
  constructor(private router: Router, public loadingCtrl: LoadingController, platform: Platform,
    public api: ApiService, public activatedRoute: ActivatedRoute, public alertController: AlertController) { }
  items: ArticleVO[] = [];
  ngOnInit() {
    this.itype = this.activatedRoute.snapshot.paramMap.get('itype');
    console.log('itype:' + this.itype);
    this.doDownRefresh(null);
    // 加载轮播图信息
    this.api.getItems<AdvertiseVO>(ApiUrl.lbt, { 'ilocation': 2 }).subscribe(response => {
      if (response != null || response.length > 0) {
        this.slideItems = response;
        // 遍历拼接url
        this.slideItems.forEach(element => {
          element.cpicpath = ApiUrl.baseUrl + element.cpicpath;
        });
      }
    });
  }
  // 下拉刷型界面
  doDownRefresh(evt) {
    if (evt === null) {
      this.onSearch('0', evt);
    } else {
      console.log('iid:' + this.items[0].iid);
      this.onSearch(this.items[0].iid, evt);
    }
  }
  onSearch(iid: string = '0', evt: any, opt: string = 'down') {
    this.api.getItems<ArticleVO>(ApiUrl.getCompanyArticle, { 'iid': iid, 'option': opt, 'itype': this.itype }).subscribe(response => {
      if (evt) {
        evt.target.complete();
      }
      if (response === null || response.length === 0) {
        console.log('没有数据返回');
        return;
      }
      console.log(opt);
      console.log(response);
      if (opt === 'down') { // 下拉刷新，把items追加到新的数据的尾部
        // this.items = this.items.concat(response);
        this.items = response.concat(this.items);
      } else {
        this.items = this.items.concat(response);
        // this.items = this.items.splice(0, 0, response);
      }
    }, () => {
      if (evt) {
        evt.target.complete();
      }
      console.log('出错了');
    });
  }
  doUpRefresh(evt) {
    console.log('上拉刷新');
    this.onSearch(this.items[this.items.length - 1].iid, evt, 'up');
  }

  goToDetails(iid) {
    this.router.navigate(['/article', { 'iid': iid }]);
  }
}
